package com.cn.ycy.service;

import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
//@ManagedResource(objectName = "sample:name=blacklist", description = "Blacklist of IP addresses")
@ManagedResource(description = "Blacklist of IP addresses")
public class JMXBlacklistMBean {

  public Set<String> ips = new HashSet<>();

  //对于属性，使用@ManagedAttribute注解标注。
  @ManagedAttribute(description = "Get IP addresses in blacklist")
  public String[] getBlacklist() {
    return ips.toArray(new String[ips.size()]);
  }

  //对于操作，使用@ManagedOperation注解标准。
  @ManagedOperation
  @ManagedOperationParameter(name = "ip", description = "Target IP address that will be added to blacklist")
  public void addBlacklist(String ip) {
    ips.add(ip);
  }

  @ManagedOperation
  @ManagedOperationParameter(name = "ip", description = "Target IP address that will be removed from blacklist")
  public void removeBlacklist(String ip) {
    ips.remove(ip);
  }

  public boolean shouldBlock(String ip) {
    return ips.contains(ip);
  }
}
